<?php
require("../connection.php");
$connection=mysql_connect($server,$username,$password);
if($connection){
  require_once ('../include/JSON.php');
  $json = new Services_JSON();
	$database=mysql_select_db($db, $connection);
	if(isset($_POST["sid"])){
  $sql="SELECT *
		FROM magove_t_spend_".$_POST["mag_spend"].
    " WHERE sid=".$_POST["sid"];
  	$query=mysql_query($sql);
    $row=mysql_fetch_array($query);
    $return_array='{"sid":"'.$row["sid"].'", "OT":"'.$row["mag_id"].'","date":"'.$row["mag_date_".$_POST["mag_spend"]].'", ';
		switch ($_POST["mag_spend"]){
      case "labor":
        $return_array.='"hours":"'.$row["mag_hours"].'", "type":"'.$row["mag_type_labor"].'", "part":"'.$row["mag_part"].'"}';
        break;
      case "buy":
        $return_array.='"factura":"'.$row["mag_factura"].'","concept":'.$json->encode($row["mag_concept_buy"]).', "cost":"'.$row["mag_cost_buy"].'"}';
        break;
      case "storage":
        $return_array.='"order":"'.$row["mag_order_storage"].'","concept":'.$json->encode($row["mag_concept_storage"]).', "cost":"'.$row["mag_cost_storage"].'"}';
        break;
    }
  }
  else{
  $sql="SELECT *
		FROM magove_t_spend_".$_POST["mag_spend"].
  ($_POST["mag_spend"]=="labor" ? " JOIN magove_t_labor_price on mag_labor=mag_type_labor" : "").
  " WHERE mag_id=".$_POST["mag_id"]."
    AND active=1
    ORDER BY mag_date_".$_POST["mag_spend"].";";
	$query=mysql_query($sql);
  $return_array='{"spend":[ ';
  while($row=mysql_fetch_array($query)){
    $return_array.='{"id": "'.$row["sid"].'", "date":"'.$row["mag_date_".$_POST["mag_spend"]].'","cost":"'.number_format($row["mag_cost_".$_POST["mag_spend"]],2).'"';
    if($_POST["mag_spend"]=="labor")
      $return_array.=',"type": "'.$row["mag_labor_desc"].'"';
    $return_array.='},';
  }
  $connection=mysql_close();
  $return_array[strlen($return_array)-1]=']';
  $return_array.='}';
  }
  echo $return_array;
}
else{
  echo '{""}';
}
?>
